package cn.innosmart.aq.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.tutk.p2p.ConnectionEntity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.DeviceListAdapter;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.camera.models.CameraBean;
import cn.innosmart.aq.customize.AddDevicePopupWindow;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.customize.DeviceFunctionPopupWindow;
import cn.innosmart.aq.customize.InputDialog;
import cn.innosmart.aq.manager.CameraManager;
import cn.innosmart.aq.manager.DeviceManager;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.util.VibratorUtil;
import cn.innosmart.aq.view.activity.AddCameraActivity;
import cn.innosmart.aq.view.activity.BoxDetailActivity;

/**
 * Created by David on 2015/7/23.
 */
public class BoxDetailManagerFragment extends BaseFragment {
    private final int ADDCAMERA = 1;
    private final int REMOVEFAILED = 18;
    private final int DATACHANGE = 0;
    private View view;
    private ListView lv_device_item;
    private ConnectionEntity connectionEntity;
    private DeviceListAdapter deviceListAdapter;
    private TextView tv_info;
    private BoxDetailActivity activity;
    private DeviceBean deviceFunction;
    private AddDevicePopupWindow addDevicePopupWindow;
    //设置Popupwindow
    private DeviceFunctionPopupWindow deviceFunctionPopupWindow;
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            deviceFunctionPopupWindow.dismiss();
            switch (v.getId()) {
                case R.id.tv_delete:
                    //删除设备
                    showLoadingDialog(getActivity());
                    SystemConstant.isExcluding = true;
                    DeviceManager.getInstance().StartExclude(connectionEntity);
                    break;
//                case R.id.tv_replace_device:
//                    showToast("功能开发中!");
//                    break;
                case R.id.tv_delete_fail:
                    //删除失效设备
                    activity.loadingDialog(getActivity(), activity.getString(R.string.fragment_manager_deleting));
                    BoxDetailActivity.getHandler().sendEmptyMessageDelayed(REMOVEFAILED, 30000);
                    SystemConstant.isRemoveFailedNode = true;
                    JSONObject jsonParams = new JSONObject();
                    try {
                        jsonParams.put("address", deviceFunction.getAddress());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //发送删除失效设备的指令
                    DeviceManager.getInstance().RemoveFailedNode(connectionEntity, jsonParams.toString());
                    break;
            }
        }
    };
    /**
     * 设置Toolbar
     */
    private Toolbar toolbar;
    private boolean isModify = false;
    private Menu menus;
    private AquariumBean aquariumBean;
    //菜单监听器
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_add_aquarium:
                    //添加设备
                    showAddDevicePopupWindow();
                    break;
                case R.id.action_edit_aquarium:
                    //编辑状态
                    isModify = !isModify;
                    if (isModify) {
                        menuItem.setTitle(getActivity().getString(R.string.action_exit_edit));
                    } else {
                        menuItem.setTitle(getActivity().getString(R.string.action_enter_edit));
                    }
                    if (isModify) {
                        menus.findItem(R.id.action_add_aquarium).setVisible(false);
                    } else {
                        menus.findItem(R.id.action_add_aquarium).setVisible(true);
                    }
                    deviceListAdapter.startModify(isModify);
                    break;
            }
            return true;
        }

    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATACHANGE:
                    deviceListAdapter.refreshData(aquariumBean);
                    deviceListAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    private View.OnClickListener listviewOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_modify_device:
                    //修改设备
                    Object object = v.getTag();
                    if (object instanceof DeviceBean) {
                        DeviceBean deviceBean = (DeviceBean) object;
                        showModifyDevice(deviceBean);
                    } else if (object instanceof CameraBean) {
//                        修改摄像头
                        CameraBean cameraBean = (CameraBean) object;
                        Intent modifyCameraIntent = new Intent(getActivity(), AddCameraActivity.class);
                        modifyCameraIntent.putExtra("flag", 2);
                        modifyCameraIntent.putExtra("CamUid", cameraBean.getUid());
                        startActivity(modifyCameraIntent);
                    }
                    break;
                case R.id.iv_delete_device:
                    Object object1 = v.getTag();
                    if (object1 instanceof CameraBean) {
                        //删除摄像头
                        showLoadingDialog(getActivity());
                        final CameraBean cameraBean = (CameraBean) object1;
                        CameraManager.getInstance().Remove(connectionEntity, cameraBean.toRemoveParam(), new CameraManager.RemoveCallBack() {
                            @Override
                            public void onRemoveResponseCallBack(int ret) {
                                hideLoadingDialog();
                                if (ret == 0) {
                                    for (int i = 0; i < SystemConstant.currentAquariumBean.getCameras().size(); i++) {
                                        if (cameraBean.getUid().equals(SystemConstant.currentAquariumBean.getCameras().get(i))) {
                                            SystemConstant.currentAquariumBean.getCameras().remove(i);
                                        }
                                    }
                                    if (activity.getCurrentCamera() != null) {
                                        if (activity.getCurrentCamera().getUid().equals(cameraBean.getUid())) {
                                            cameraBean.disConnect();
                                            activity.setCurrentCamera(null);
                                        }
                                    }
                                    SystemConstant.cameraBeanHashMap.remove(cameraBean.getUid());
                                    showToast(activity.getString(R.string.delete_success));
                                } else {
                                    showToast(activity.getString(R.string.delete_failed));
                                }
                                mHandler.sendEmptyMessage(DATACHANGE);
                            }
                        });
                    } else if (object1 instanceof DeviceBean) {
                        //删除设备
                        deviceFunction = (DeviceBean) v.getTag();
                        VibratorUtil.getInstance().vibrator(getActivity().getApplicationContext(), 100);
                        showDevicePopupWindow();
                    }
                    break;
            }
        }
    };

    public void setConnectionEntity(ConnectionEntity connectionEntity) {
        this.connectionEntity = connectionEntity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_manager, container, false);
        lv_device_item = (ListView) view.findViewById(R.id.lv_device_item);
        tv_info = (TextView) view.findViewById(R.id.tv_info);
        deviceListAdapter = new DeviceListAdapter(getActivity());
        deviceListAdapter.setOnclickListener(listviewOnClickListener);
//        deviceListAdapter.setOnLongClickListener(onLongClickListener);
        lv_device_item.setAdapter(deviceListAdapter);
        activity = (BoxDetailActivity) getActivity();
        setHasOptionsMenu(true);
        setBar();
        return view;
    }

    /**
     * 添加设备的弹出层
     */
    private void showAddDevicePopupWindow() {
        addDevicePopupWindow = new AddDevicePopupWindow(getActivity(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_add_camera:
                        //添加摄像头
                        addDevicePopupWindow.dismiss();
                        Intent addCameraIntent = new Intent(getActivity(), AddCameraActivity.class);
                        addCameraIntent.putExtra("flag", 1);
                        startActivityForResult(addCameraIntent, ADDCAMERA);
                        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        break;
                    case R.id.btn_add_device:
                        //添加设备
                        addDevicePopupWindow.dismiss();
//                        if (SystemConstant.MODE == SystemConstant.PERSONALMODE) {
//                            ArrayList<String> devices = aquariumBean.getDeivices();
//                            HashMap<String, String> devicesize = new HashMap<>();
//                            for (int i = 0; i < devices.size(); i++) {
//                                String address = (String) devices.get(i);
//                                String[] addresss = address.split("/");
//                                devicesize.put(addresss[3], "1");
//                            }
//                            if (devicesize.size() >= 10) {
//                                deviceSizeAlert();
//                                break;
//                            }
//                        }
                        if (SystemConstant.isIncluding == true) {
                            //已经处于including模式，所以，不会重复
                            break;
                        }
                        SystemConstant.isIncluding = true;
                        DeviceManager.getInstance().StartExclude(connectionEntity);
                        break;
                }
            }
        });
        addDevicePopupWindow.showAtLocation(getActivity().findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {


    }

    /**
     * 显示删除设备的弹出层
     */
    private void showDevicePopupWindow() {
        deviceFunctionPopupWindow = new DeviceFunctionPopupWindow(getActivity(), itemsOnClick);
        deviceFunctionPopupWindow.showAtLocation(getActivity().findViewById(R.id.main), Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 设置Toolbar
     */
    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        if (aquariumBean != null) {
            //根据设备数量显示菜单内容
            if (aquariumBean.getDeivices().size() != 0 || aquariumBean.getCameras().size() != 0) {
                menu.findItem(R.id.action_edit_aquarium).setVisible(true);
            } else {
                //没有设备和摄像头时，编辑菜单将不显示
                menu.findItem(R.id.action_edit_aquarium).setVisible(false);
                menus.findItem(R.id.action_add_aquarium).setVisible(true);
                isModify = false;
                deviceListAdapter.startModify(isModify);
            }
            //编辑状态模式改变
            if (isModify) {
                menu.findItem(R.id.action_edit_aquarium).setTitle(getActivity().getString(R.string.action_exit_edit));
            } else {
                menu.findItem(R.id.action_edit_aquarium).setTitle(getActivity().getString(R.string.action_enter_edit));
            }
            if (isModify) {
                menus.findItem(R.id.action_add_aquarium).setVisible(false);
            } else {
                menus.findItem(R.id.action_add_aquarium).setVisible(true);
            }
        }
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_boxdetail_all, menu);
        menu.findItem(R.id.action_message).setVisible(false);
        if (aquariumBean != null) {
            if (aquariumBean.getDeivices().size() == 0)
                menu.findItem(R.id.action_edit_aquarium).setVisible(false);
        }
        menus = menu;
        super.onCreateOptionsMenu(menu, inflater);
    }

    /**
     * 设置鱼缸
     *
     * @param aquarium
     */
    public void setAquarium(AquariumBean aquarium) {
        this.aquariumBean = aquarium;
    }

    @Override
    public void onResume() {
        getActivity().invalidateOptionsMenu();
        if (aquariumBean != null) {
            deviceListAdapter.refreshData(aquariumBean);
            if (aquariumBean.getDeivices().size() != 0 || aquariumBean.getCameras().size() != 0) {
                //  如果设备或者摄像头不为空，则不显示提示信息
                tv_info.setVisibility(View.GONE);
            } else {
                //如果设备或者摄像头为空，则显示提示信息
                tv_info.setVisibility(View.VISIBLE);
            }
        }
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    /**
     * 做多添加10个设备的警告对话框
     */
    private void deviceSizeAlert() {
        final CustomsizeDialog sizeAlertDialog = new CustomsizeDialog(getActivity());
        sizeAlertDialog.setTitle(getActivity().getString(R.string.dialog_title_alert));
        sizeAlertDialog.setContent(activity.getString(R.string.fragment_manager_device_limit));
        sizeAlertDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sizeAlertDialog.dismiss();
            }
        });
        sizeAlertDialog.show();
    }

    /**
     * 显示修改设备名称的对话框
     *
     * @param deviceBean
     */
    private void showModifyDevice(final DeviceBean deviceBean) {
        final EditText etName;
        final InputDialog deviceNameModifyDialog = new InputDialog(getActivity());
        etName = (EditText) deviceNameModifyDialog.findViewById(R.id.et_name);
        etName.setText(deviceBean.getName());
        deviceNameModifyDialog.setHint(getString(R.string.title));
        deviceNameModifyDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String name = etName.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    showToast(getActivity().getString(R.string.deviec_name_can_not_empty));
                    return;
                }
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("name", name);
                    jsonObject.put("label", name);
                    jsonObject.put("address", deviceBean.getAddress());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                showLoadingDialog(getActivity());
                //发送设备更新的指令
                DeviceManager.getInstance().Update(connectionEntity, jsonObject.toString(), new DeviceManager.UpdateCallBack() {
                    @Override
                    public void onUpdateResponseCallBack(int ret) {
                        if (ret == 0) {
                            deviceBean.setName(name);
                            hideLoadingDialog();
                            deviceNameModifyDialog.dismiss();
                            mHandler.sendEmptyMessage(DATACHANGE);
                        } else {
                            hideLoadingDialog();
                            deviceNameModifyDialog.dismiss();
                            showToast(getActivity().getString(R.string.device_name_modify_failed));
                        }
                    }
                });
            }
        });
        deviceNameModifyDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deviceNameModifyDialog.dismiss();
            }
        });
        deviceNameModifyDialog.show();
    }
}
